﻿using Quartz;
using Serilog;
using Serilog.Events;
using System.Runtime.InteropServices;
using WeWork.Service.Core.Extensions;
using WeWork.Service.Core.Jobs;

var builder = Host.CreateApplicationBuilder(args);

Log.Logger = new LoggerConfiguration()
//.MinimumLevel.Error() //只记录错误日志
//需要引用 Serilog.Configuration包
//.ReadFrom.Configuration(configuration)
//.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
// 添加代码配置
//需要引用 Serilog.Enrichers.Environment包
//.Enrich.WithMachineName()
//.Enrich.WithEnvironmentUserName()

//错误日志分离‌
.WriteTo.Logger(lc => lc.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Error))
//.WriteTo.File(Path.Combine(AppContext.BaseDirectory, "Logs", "errors-.log"), rollingInterval: RollingInterval.Day)
//.WriteTo.Logger(lc => lc.Filter.ByExcluding(e => e.Level == LogEventLevel.Error)
//.WriteTo.File(Path.Combine(AppContext.BaseDirectory, "Logs", "other-.log"), rollingInterval: RollingInterval.Day))

//.WriteTo.Console()
//.WriteTo.File(Path.Combine(AppContext.BaseDirectory, "Logs", "log-.log"), rollingInterval: RollingInterval.Day)

//需要引用 Serilog.Sinks.Async包
.WriteTo.Async(a => a.File(Path.Combine(AppContext.BaseDirectory, "Logs", "log-.log"), rollingInterval: RollingInterval.Day))

//需要引用 Elasticsearch
//.WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri("http://localhost:9200")))
.CreateLogger();

// 替换ASP.NET Core的默认日志为Serilog
var logging = builder.Logging;
logging.ClearProviders();
logging.AddSerilog(); //需要引用 Serilog.AspNetCore 

// Windows 平台
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
    //需要引用包 Microsoft.Extensions.Hosting.WindowsServices
    builder.Services.AddWindowsService();// 启用Windows服务支持
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
    //需要引用包 Microsoft.Extensions.Hosting.Systemd
    builder.Services.AddSystemd();// 配置为Linux系统服务
}

//builder.Services.AddHostedService<Worker>();

// Add the required Quartz.NET services
builder.Services.AddQuartz(q =>
{
    //从Quartz.NET 3.1版本开始，MicrosoftDependencyInjectionJobFactory已成为默认的作业工厂实现，不再需要显式调用此方法
    //q.UseMicrosoftDependencyInjectionJobFactory();

    // Register the job, loading the schedule from configuration
    //q.AddJobAndTrigger<HelloWorldJob>(builder.Configuration);

    q.ExecuteByCron<HelloWorldJob>("0 0/1 * * * ?");
    q.ExecuteByCron<SendEmailJob>("0 0/2 * * * ?");
});
// WaitForJobsToComplete:此设置确保当请求关闭时，Quartz.NET在退出之前等待作业优雅地结束。
builder.Services.AddQuartzHostedService(q => q.WaitForJobsToComplete = true);

var host = builder.Build();
host.Run();
